using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace tutFuelCellGame
{
    public class InputManager : GameComponent
    {
        private GamePadState previousGamePadState;
        private GamePadState currentGamePadState;
        private KeyboardState previousKeyboardState;
        private KeyboardState currentKeyboardState;

        public InputManager(Game game)
            : base(game)
        {

        }

        public bool IsExitPressed
        {
            get { return IsKeyDown(Keys.Escape) || IsButtonPressed(Buttons.Back); }
        }

        public float TurnAmount
        {
            get
            {
                var x = currentGamePadState.ThumbSticks.Left.X;
                if (IsKeyDown(Keys.Left)) x = 1;
                if (IsKeyDown(Keys.Right)) x = -1;
                return x;
            }
        }

        public float Thrust
        {
            get
            {
                var y = MathHelper.Clamp(currentGamePadState.ThumbSticks.Left.Y, 0f, 1f);
                if (IsKeyDown(Keys.Up)) y = 1;
                //if (IsKeyDown(Keys.Down)) y = -1;
                return y;
            }
        }

        public bool StartPressed
        {
            get
            {
                return IsButtonPressed(Buttons.Start) ||
                       IsKeyPressed(Keys.Space);
            }
        }

        public bool IsKeyPressed(Keys aKey)
        {
            return currentKeyboardState.IsKeyDown(aKey) &&
                   previousKeyboardState.IsKeyUp(aKey);
        }
 
        public bool IsButtonPressed(Buttons button)
        {
            return currentGamePadState.IsButtonDown(button);
        }

        public bool IsKeyDown(Keys key)
        {
            return currentKeyboardState.IsKeyDown(key);
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            previousKeyboardState = currentKeyboardState;
            previousGamePadState = currentGamePadState;

            currentKeyboardState = Keyboard.GetState();
            currentGamePadState = GamePad.GetState(PlayerIndex.One);
        }
    }
}